// baseinfo.js
const UTIL = require('../../utils/util.js');
const qiniuUploader = require('../../utils/qiniuUploader.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    steps: [
      { text: '注册', right: true, left: false, doneClass: 'done'},
      { text: '填写基本资料', right: true, left: true, doneClass: 'done' },
      { text: '填写认证资料', right: false, left: true, doneClass: '' }
    ],
    nickname: '',
    weixin: '',
    mobilePrefix: '81',
    phone: '',
    uptoken: '',
    avatar: '',
    album: [],
    idImg: [],
    birthdate: '1990-01-01',
    submitState: true,
    currentStepIdx: 1,
    areaCodeIdx: 0,
    areaCodes: ["81", "82", "852", "853", "886", "66", "44", "1", "33", "64", "52", "971", "63", "855", "856", "960", "60", "95", "977", "94", "65", "91", "62", "84", "43", "32", "354", "48", "45", "49", "7", "379", "358", "31", "420", "385", "352", "377", "47", "351", "46", "41", "421", "90", "34", "30", "36", "39", "20", "377", "1", "61", "356", "593", "55", "7", "51", "56", "54", "386", "1849", "86", "248", "380", "680", "372", "53", "230", "92", "679", "689"],
    liveInfo: '',
    tagsInfo: '',
    briefComment: '',
    intro: '',
    authInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.step) {
      this.setData({
        currentStepIdx: options.step
      });
    }
    this.setData({
      yxInfo: UTIL.Login.getYxInfo()
    });
    wx.request({
      url: 'https://www.zuihuiyou.cc/token/avatar',
      success: (res) => {
        this.setData({
          uptoken: res.data
        });
      },
      fail: function(err) {
        wx.showModal({
          title: '图片上载token获取失败，请重新打开小程序，并联系Mr. Dev',
          content: '',
          showCancel: false
        });
        console.log(err);
      }
    });
    console.log(JSON.stringify(options));
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    /*wx.request({
      url: 'https://www.zuihuiyou.cc/api/resource/static/countryAndCity',
      success: function(res) {
        console.log(res.data);
      }
    })*/
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      avatar: UTIL.Login.getAvatar(),
      realName: UTIL.Login.getRealName(),
      email: UTIL.Login.getYxInfo().email,
      password: UTIL.Login.getYxInfo().password,
      liveInfo: UTIL.Login.getLivePlace()[0] == '' ? '请选择' : UTIL.Login.getLivePlace().join('，'),
      tagsInfo: UTIL.Login.getTags()[0] == '' ? '请选择' : UTIL.Login.getTags().join('，'),
      areaCodeIdx: UTIL.Login.getRegionIdx(),
      briefComment: UTIL.Login.getBriefComment(),
      authInfo: UTIL.Login.getAuthInfo().authImg == '' ? '请选择' : UTIL.Login.getAuthInfo(),
      album: UTIL.Login.getImgs().length == 0 ? [] : UTIL.Login.getImgs(),
      intro: UTIL.Login.getIntro(),
      discription: UTIL.Login.getCityLifeInfo() + UTIL.Login.getServiceInfo() + UTIL.Login.getTripInfo()
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "游侠注册，就找最会游，专业、认真、靠谱",
      path: "/pages/index/index"
    }
  },

  nicknameInput: function(e) {
    let value = e.detail.value;
    if(value && value.trim() != '') {
      this.setData({
        nickname: e.detail.value
      });
    }else {
      wx.showToast({
        title: '请填写昵称',
      });
    }
  },

  weixinInput: function(e) {
    let value = e.detail.value;
    if (value && value.trim() != '') {
      this.setData({
        weixin: e.detail.value
      });
    } else {
      wx.showToast({
        title: '请填写微信号',
      });
    }
  },

  phoneInput: function(e) {
    let value = e.detail.value;
    if (value && value.trim() != '') {
      this.setData({
        phone: e.detail.value
      });
    } else {
      wx.showToast({
        title: '请填写当地电话',
      });
    }
  },

  bindAreaCodeChange: function(e) {
    this.setData({
      areaCodeIdx: e.detail.value,
      mobilePrefix: this.data.areaCodes[e.detail.value]
    });
  },

  gotoLocSelect: function() {
    wx.navigateTo({
      url: '../location/location',
    });
  },

  next: function() {
    this.data.steps[2].doneClass = 'done';
    this.setData({
      currentStepIdx: 2,
      steps: this.data.steps
    });
  },

  uploadAvatar: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        let tempFilePath = res.tempFilePaths[0];
        wx.showLoading({
          title: '图片上载中，耐心等候'
        });
        qiniuUploader.upload(tempFilePath, (res) => {
          that.setData({
            avatar: 'https://' + res.imageURL + '?imageView2/1/w/80/h/80/format/jpg/'
            //avatar: 'http://' + res.imageURL
          });
          UTIL.Login.setAvatar(that.data.avatar);
          /*wx.previewImage({
            current: that.data.avatar,
            urls: [that.data.avatar],
          });*/
          console.log('avatar: ' + that.data.avatar);
          wx.hideLoading();
        },
        (err) => {
          wx.hideLoading();
        }, 
        {
          region: 'ECN',
          domain: 'icon.zuihuiyou.cn',
          uptoken: that.data.uptoken
        });
      },
      fail: function() {
        wx.hideLoading();
      }
    });
  },
  gotoAlbum: function() {
    wx.navigateTo({
      url: './uploadavatar/uploadavatar',
    })
  },

  gotoIDInfo: function() {
    wx.navigateTo({
      url: './uploadIDinfo/uploadIDinfo',
    })
  },

  gotoTags: function() {
    wx.navigateTo({
      url: './tags/tags',
    })
  },

  realNameInput: function(e) {
    if(e.detail.value.trim() != '') {
      this.setData({
        realName: e.detail.value
      });
    }else {
      wx.showToast({
        title: '请填写姓名',
      });
    }
  },

  genderChange: function(e) {
    this.setData({
      gender: e.detail.value
    });
  },

  birthdateChange: function(e) {
    this.setData({
      birthdate: e.detail.value
    });
  },

  gotoFeature: function() {
    wx.navigateTo({
      url: './features/features',
    })
  },

  gotoBrief: function() {
    wx.navigateTo({
      url: './brief/brief',
    })
  },
  
  gotoStory: function() {
    wx.navigateTo({
      url: './story/yxstory',
    })
  },

  registerYx: function() {
    let authInfo = UTIL.Login.getAuthInfo();
    let yxInfo = {
      briefComment: this.data.briefComment,
      country: this.data.liveInfo.split('，')[0],
      city: this.data.liveInfo.split('，')[1],
      duration: this.data.liveInfo.split('，')[2],
      email: this.data.email,
      password: this.data.password,
      nickname: this.data.nickname,
      gender: this.data.gender,
      intro: this.data.intro,
      weixin: this.data.weixin,
      mobilePrefix: this.data.mobilePrefix,
      phone: this.data.phone,
      description: '',
      tags: this.data.tagsInfo,
      album: {imgs: this.data.album},
      headImg: this.data.headImg,
      birthday: this.data.birthday,
      authType: authInfo.authType || '',
      authImg: authInfo.authImg || '',
      authImg2: authInfo.authImg2 || '',
      idNumber: authInfo.idNumber || ''
    };
    wx.showLoading({
      title: '注册信息提交中',
    });
    wx.request({
      url: 'https://www.zuihuiyou.cc/signup',
      method: 'POST',
      data: yxInfo,
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200 || res.statusCode == 201) {
          wx.redirectTo({
            url: '../done/done',
          });
          UTIL.Login().resetAll();
        }else {
          wx.showModal({
            title: res.data && res.data.message || '注册失败'
          })
        }
        
      },
      fail: function(err) {
        wx.showModal({
          title: '注册失败',
          content: JSON.stringify(err),
          showCancel: false
        });
        wx.hideLoading();
      }
    })
  }
})